package com.agileai.bpm.controller.running;

import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.bpm.controller.emulation.ProcessHelper;
import com.agileai.bpm.webservice.BPMService;
import com.agileai.bpm.webservice.BizAttribute;
import com.agileai.bpm.webservice.LaunchWorkItem;
import com.agileai.bpm.webservice.SubmitWorkItem;
import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.MemSecrityKeys;
import com.agileai.hotweb.common.ResultStatus;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class ProcessInvokerHandler extends BaseHandler{

	@PageAction
	public ViewRenderer start(DataParam param){
		String responseText = "";
		try {
			String tokenId = param.get("tokenId");
			String memSecrityKey = MemSecrityKeys.getSecrityKey(tokenId);
			if (memSecrityKey != null && tokenId.equals(memSecrityKey)){
				String inputString = this.getInputString();
				if (StringUtil.isNotNullNotEmpty(inputString)){
					JSONObject jsonObject = new JSONObject(inputString);
					
					String processCode = jsonObject.getString("processCode");
					String bizTitle = jsonObject.getString("bizTitle");
					String recordId = jsonObject.getString("recordId");
					String userCode = jsonObject.getString("userCode");
					boolean skipFirstNode = jsonObject.getBoolean("skipFirstNode");
					
					ProcessHelper processHelper = ProcessHelper.instance();
					BPMService bpmService = processHelper.getBPMService();
					
					String processId = bpmService.getCurrentProcessId(processCode);
					LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
					launchWorkItem.setTitle(bizTitle);
					launchWorkItem.setBizRecordId(recordId);
					launchWorkItem.setUserCode(userCode);
					
					JSONArray attributes = jsonObject.getJSONArray("attributes");
					if (attributes != null){
						List<BizAttribute> attributeList = launchWorkItem.getAttributeList();
						int length = attributes.length();
						for (int i=0;i < length;i++){
							JSONObject attributeObject = attributes.getJSONObject(i);
							BizAttribute attribute = new BizAttribute();
							String code = attributeObject.getString("code");
							String value = attributeObject.getString("value");
							attribute.setCode(code);
							attribute.setValue(value);
							attributeList.add(attribute);
						}
					}
					
					ResultStatus resultStatus = bpmService.launchProcess(launchWorkItem,skipFirstNode);
					responseText = buildResponseText(resultStatus);	
				}else{
					ResultStatus resultStatus = new ResultStatus();
					resultStatus.setErrorCode("-1");
					resultStatus.setSuccess(false);
					resultStatus.setErrorMsg("request json data is empty !");
					responseText = buildResponseText(resultStatus);
				}
			}else{
				ResultStatus resultStatus = new ResultStatus();
				resultStatus.setSuccess(false);
				resultStatus.setErrorCode("-1");
				resultStatus.setErrorMsg("tokenId is not exists or is not valid !");
				responseText = buildResponseText(resultStatus);
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer watch(DataParam param){
		String responseText = "";
		try {
			String tokenId = param.get("tokenId");
			String memSecrityKey = MemSecrityKeys.getSecrityKey(tokenId);
			if (memSecrityKey != null && tokenId.equals(memSecrityKey)){
				String inputString = this.getInputString();
				if (StringUtil.isNotNullNotEmpty(inputString)){
					JSONObject jsonObject = new JSONObject(inputString);
					
					String processId = jsonObject.getString("processId");
					String processInstId = jsonObject.getString("processInstId");
					String activityCode = jsonObject.getString("activityCode");
				
					ProcessHelper processHelper = ProcessHelper.instance();
					BPMService bpmService = processHelper.getBPMService();
				
					SubmitWorkItem processWorkItem = processHelper.createSubmitWorkItem(processId, processInstId, activityCode);
					JSONArray attributes = jsonObject.getJSONArray("attributes");
					if (attributes != null){
						List<BizAttribute> attributeList = processWorkItem.getAttributeList();
						int length = attributes.length();
						for (int i=0;i < length;i++){
							JSONObject attributeObject = attributes.getJSONObject(i);
							BizAttribute attribute = new BizAttribute();
							String code = attributeObject.getString("code");
							String value = attributeObject.getString("value");
							attribute.setCode(code);
							attribute.setValue(value);
							attributeList.add(attribute);
						}
					}
					ResultStatus resultStatus = bpmService.submitProcess(processWorkItem);
					responseText = buildResponseText(resultStatus);	
				}else{
					ResultStatus resultStatus = new ResultStatus();
					resultStatus.setErrorCode("-1");
					resultStatus.setSuccess(false);
					resultStatus.setErrorMsg("request json data is empty !");
					responseText = buildResponseText(resultStatus);
				}
			}else{
				ResultStatus resultStatus = new ResultStatus();
				resultStatus.setErrorCode("-1");
				resultStatus.setSuccess(false);
				resultStatus.setErrorMsg("tokenId is not exists or is not valid !");
				responseText = buildResponseText(resultStatus);
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	private String buildResponseText(ResultStatus resultStatus){
		String result = null;
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("isSuccess",resultStatus.isSuccess());
			jsonObject.put("errorCode", resultStatus.getErrorCode());
			jsonObject.put("errorMsg", resultStatus.getErrorMsg());
			result = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return result;
	}
}
